﻿using System.Linq;
using Contracts.Entities;

namespace Model.MovieElements
{
    public class WriteDirectors : WriteMovieElement
    {
        public WriteDirectors(MovieDatabaseEntities entities, Movies movie)
            : base(entities, movie)
        {
        }

        public override void Insert(MovieElement element)
        {
            var entity = entities.Directors.SingleOrDefault(m => m.Name == element.Name);
            if (entity == null)
            {
                entity = DirectorConverter.GetEntity(element);
                entity.Id = GetLastID() + 1;
            }

            movie.Directors.Add(entity);
            entities.SaveChanges();
        }

        public override void Delete(MovieElement element)
        {
            var director = movie.Directors.SingleOrDefault(m => m.Id == element.Id);
            
            if (director == null)
                return;

            movie.Directors.Attach(director);
            movie.Directors.Remove(director);
            entities.SaveChanges();
        }

        private int GetLastID()
        {
            var director = entities.Directors.OrderByDescending(m => m.Id).FirstOrDefault();
            return director != null ? director.Id : 0;
        }

        public override MovieElementType GetMovieElementType()
        {
            return MovieElementType.Director;
        }
    }
}
